//
//  DataSyncHelper.m
//  test
//
//  Created by mac on 2017/9/14.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "DataSyncHelper.h"
#import "DBManagerHelper.h"
#import "Product.h"
#import "TestDB.h"

@implementation DataSyncHelper

-(void) sync:(void (^)(BOOL res))callback{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSDictionary *parameters = @{ @"deviceid" : @"74b4f16c9dd55c5714f62648341c1feb79bea6d0"
                                  ,@"last_sync_date" : @"2000-1-1"
                                  ,@"page_index" : @"1"
                                  ,@"page_size" : @"100"};
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [manager POST:@"http://58.210.187.2:9999/Interface/GetCase.ashx" parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //report_date | post_code | store_name | brand | reason_name
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            //删除数据
           // [[DBManagerHelper instance]delectFrom];
           // NSLog(@"数据删除成功");
            //添加数据
           // NSArray *datas = [responseObject objectForKey:@"return_obj"];
            
           // [[DBManagerHelper instance]batchInsert:datas];
            //sleep(3);
            
            //查询分类
            
            //FMResultSet *set = [[DBManagerHelper instance]selectCategory];
           /* while ([set next]) {
                NSLog(@"===%@====%@",[set stringForColumn:@"brand"],[set stringForColumn:@"total"]);
            }*/
            //查询总量
            int count =[[DBManagerHelper instance]selectCount];;
            NSLog(@"count=%i",count);
            
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // NSLog(@"===========%@", error);
    }];
    
}

-(void)insertProduct:(NSDictionary *)responseObject {
    NSArray *datas = [responseObject objectForKey:@"return_obj"];
    for (NSDictionary *item in datas) {
        Product *model=[[Product alloc]init];
        model.report_date = [item objectForKey:@"report_date"];
        model.post_code = [item objectForKey:@"post_code"];
        model.store_name = [item objectForKey:@"store_name"];
        model.brand = [item objectForKey:@"brand"];
        model.reason_name = [item objectForKey:@"reason_name"];
        [[DBManagerHelper instance] insertProduct:model];
    }
    
    FMResultSet *set = [[DBManagerHelper instance]selectCategory];
    while ([set next]) {
        NSLog(@"===%@====%@",[set stringForColumn:@"brand"],[set stringForColumn:@"total"]);
    }
    int count =[[DBManagerHelper instance]selectCount];;
    NSLog(@"count=%i",count);
}





@end
